#!/usr/bin/env groovy
@Library('CI_Script')
import com.yidao.www.*;

def java = [
    [
        'name' : 'D200',
        'branch' : 'dev-deep-ui',
        'language' : 'java',
        'webhookUrl' : '',
        'profile' : ''
    ]
]

def web = [
    [
        'name' : 'd200-web',
        'branch' : 'dev',
        'manuallyTrigger' : true
    ]
]

def x86Robot = [
//    [
//        'name' : 'D200',
//        'arch' : 'x86_64',
//        'branch' : 'dev-gamma-new',
//        'distro' : '16.04'
//    ]
]

def armRobot = [
//    [
//        'name' : 'D200',
//        'arch' : 'aarch64',
//        'branch' : 'dev-gamma-new',
//        'distro' : '16.04'
//    ]
]

// def robot = [
//     [
//         'name' : 'D200',
//         'arch' : 'x86_64',
//         'branch' : 'dev-gamma-new',
//         'distro' : '16.04'
//     ],
//     [
//         'name' : 'D200',
//         'arch' : 'aarch64',
//         'branch' : 'dev-gamma-new',
//         'distro' : '16.04'
//     ]
// ]

def upgradeTools = [
    [
        'name' : 'upgradeTools',
        'branch' : 'master',
        'type' : 'web',
        'robot' : 'D200'
    ],
    [
        'name' : 'upgradeTools',
        'branch' : 'master',
        'type' : 'client',
        'robot' : 'D200'
    ]
]

def calibration = [
    'name' : 'D200Calibration',
    'branch' : 'dev-gamma-new'
]

def embedProjects = [
    'D200Tr3Embed_D200_ARM_CTRL',
    'D200Tr3Embed_D200_NAVI_CTRL',
    'D200Tr3Embed_D200_NEW_CHASSIS_CTRL',
    'D200Tr3Embed_D200_NEW_EDP_CTRL',
    'D200Tr3Embed_D200_NEW_TWIST_CTRL'
]

def embedPackages = [
    'D200_ARM_CTRL',
    'D200_NAVI_CTRL',
    'D200_NEW_CHASSIS_CTRL',
    'D200_NEW_EDP_CTRL',
    'D200_NEW_TWIST_CTRL'
]


def builds = [:]
def build = new build()
def vueBuild = new vueBuild()
def base = new base()
def robotBuild = new robotBuild()
def embedBuild = new embedBuild()
def toolsBuild = new toolsBuild()
def calibrationBuild = new calibrationBuild()
def downloads = []
def clean = params.CLEAN //布尔值参数，是否全量编译
def number = BUILD_NUMBER //Jenkins 内置变量 Build_number
def robotName = params.ROBOTNAME //机器人代号 e.g. D200
def version = params.VERSION //机器人阶段号 e.g. tr1,tr2,tr3
def majorVersion = params.MAJORVERSION
def subVersion = params.SUBVERSION
def stageVersion = params.STAGEVERSION
def date = new Date()
def dateVersion = date.format('yyyyMMdd')
def letterVersion = params.LETTERVERSION
def robotDeployProfile = robotDeployProfile(robotName, number, version, 'dev-gamma-new')
println robotDeployProfile
def remoteDir = robotDeployProfile.artifactory
// def robotPackage = robotDeployProfile.packageName
def branch = 'dev-gamma-new'
def robotVersion = majorVersion + '.' + subVersion + '.' + stageVersion + '.' + dateVersion + ' ' + letterVersion + '_' + number
def buildVersion = majorVersion + '.' + subVersion + '.' + stageVersion
def packageVersion = branch + '_' + buildVersion + '.' + date.format('yyyyMMddHHmm') + '_' + number
def robotPackage = robotVersion + '.zip'
def localDir = robotDeployProfile.localDir
def localPackage = robotDeployProfile.localPackage
def config = robotDeployProfile.config
def upgradeToolsClientDownload
def calibrationDownload
def mergeDownloads = []

println '版本号:' + robotPackage

for(i = 0; i < java.size(); i++){
    def project = java[i]
    builds["${project.name}"] = {
        // try{
            def result = build.javaManuallyBuild(project.name, project.branch, project.language, project.webhookUrl, project.profile, buildVersion)
            downloads.add(result)
        // }catch(e){
        //     error e.getMessage()
        // }
    }
}

for(i = 0; i < web.size(); i++){
    def project = web[i]
    builds["${project.name}"] = {
        // try{
            def result = vueBuild.autoBuild(project.name, project.branch, project.manuallyTrigger)
            mergeDownloads.add(result)
        // }catch(e){
        //     error e.getMessage()
        // }
    }
}

for(i = 0; i < x86Robot.size(); i++){
    def project = x86Robot[i]
    builds["${project.name}-${project.arch}-${project.distro}"] = {
        // try{
            def result = robotBuild.robotAutoBuild(project.name, project.arch, project.branch, project.distro, clean, buildVersion)
            // downloads.add(result)
            mergeDownloads.add(result)
        // }catch(e){
        //     error e.getMessage()
        // }

        // branch = project.branch
    }
}

for(i = 0; i < armRobot.size(); i++){
    def project = armRobot[i]
    builds["${project.name}-${project.arch}-${project.distro}"] = {
        // try{
            def result = robotBuild.robotAutoBuild(project.name, project.arch, project.branch, project.distro, clean, buildVersion)
            downloads.add(result)
        // }catch(e){
        //     error e.getMessage()
        // }

        // branch = project.branch
    }
}

// for(i=0;i<embed.size();i++){
//     def project = embed[i]
//     builds["${project.name}"] = {
//         def result = embedBuild.autoBuild(project.name, project.branch)
//         downloads.add(result)
//     }
// }

for(i = 0; i < upgradeTools.size(); i++){
    def project = upgradeTools[i]
    builds["${project.name}-${project.type}"] = {
        // try{
            if(project.type == 'web'){
                def result = toolsBuild.autoBuildWithK8s(project.name, project.branch, project.type, project.robot, packageVersion, version, number)
                downloads.add(result)
            }else{
                def result = toolsBuild.autoBuild(project.name, project.branch, project.type, project.robot, packageVersion, version, number)
                upgradeToolsClientDownload = result
            }
        // }catch(e){
        //     error e.getMessage()
        // }

    }
}

builds["${calibration.name}"] = {
    // try{
        def result = calibrationBuild.autoBuild(calibration.name, calibration.branch, BUILD_NUMBER)
        // downloads.add(result)
        calibrationDownload = result
    // }catch(e){
    //     error e.getMessage()
    // }

}



timestamps{
    timeout(time: 3, unit: 'HOURS'){
        parallel builds
    }
    println downloads
    def server = Artifactory.server 'jfrog-artifactory'
    def mergeDownloadUrl
    def downloadUrl
    def srverUrl = server.url

    node('ZIP'){

        println '=======================merge web to install======================='
        for(mergeDownload in mergeDownloads){
            mergeDownloadUrl = mergeDownload
            println mergeDownloadUrl
            base.fileDownload(mergeDownloadUrl, localDir)
        }
        def installTarName = base.scriptStdout('ls install*.tar.gz')
        println 'install tar name: ' + installTarName
        sh "tar zxvf ${installTarName}"
        unzip dir: 'install/share/config/cfg/dist', glob: '', zipFile: 'dist.zip'
        sh "rm -f dist.zip ${installTarName}"
        sh "tar zcvf ${installTarName} install/ update.sh"
        sh "rm -rf install/ update.sh"
        println '=======================merge web to install======================='

        for(embedProject in embedProjects){
            copyArtifacts(projectName: embedProject, selector: lastSuccessful())
            sh '''
                unzip -O GBK -o *.zip
                rm -f *.zip
            '''
        }
        sh """
            zip -r OUT_`date +%Y%m%d`.zip D200_*
            rm -rf D200_* version.txt
        """
        // for i in `ls`; do if [ $i != OUT_`date +%Y%m%d`.zip ] && [ $i != ${installTarName} ]; then rm -rf $i; fi; done;
        for(download in downloads){
            println download
            downloadUrl = download
            println downloadUrl
            base.fileDownload(downloadUrl, localDir)
        }
        sh """
            echo "版本号: ${robotVersion}" > version.txt
        """

        base.zipPackage(robotPackage, localPackage)
        def deployTarget = base.backupFolder(remoteDir, '', branch, date)
        base.fileUpload(robotPackage, deployTarget)
        sh "rm -rf *"
        base.fileDownload(upgradeToolsClientDownload, localDir)
        base.fileDownload(calibrationDownload, localDir)
        base.fileUpload(localPackage, deployTarget)
        def zipStorage = srverUrl + '/' + deployTarget
        currentBuild.description = """<span>存储地址:<a href=${zipStorage}>${zipStorage}</a></span>"""
        cleanWs() //清除工作空间
    }

}